<template>
  <div class="upload-container">
    <div class="upload-box">
      <div class="logo">
        <span class="logo-cloud">新闻上传</span>
      </div>

      <el-form :model="form" class="upload-form" ref="uploadFormRef">
        <!-- 时间选择行 - 右对齐标签 -->
        <el-row class="form-row">
          <el-col :span="6" class="label-col right-align">
            <span class="form-label">时间：</span>
          </el-col>
          <el-col :span="18" class="content-col">
            <el-date-picker
                v-model="form.publish_time"
                type="datetime"
                placeholder="选择日期时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-col>
        </el-row>

        <!-- 标题输入行 - 右对齐标签 -->
        <el-row class="form-row">
          <el-col :span="6" class="label-col right-align">
            <span class="form-label">标题：</span>
          </el-col>
          <el-col :span="18" class="content-col">
            <el-input v-model="form.title" placeholder="请输入新闻标题" />
          </el-col>
        </el-row>

        <!-- 第一段内容行 - 左对齐标签 -->
        <el-row class="form-row">
          <el-col :span="6" class="label-col left-align">
            <span class="form-label">第一段文字内容：</span>
          </el-col>
          <el-col :span="18" class="content-col">
            <el-input
                v-model="form.paragraph1"
                type="textarea"
                :rows="4"
                placeholder="请输入第一段文字内容"
                class="content-textarea"
            />
          </el-col>
        </el-row>

        <!-- 配图上传行 - 右对齐标签 -->
        <el-row class="form-row">
          <el-col :span="6" class="label-col right-align">
            <span class="form-label">配图：</span>
          </el-col>
          <el-col :span="18" class="content-col">
            <el-upload
                class="upload-dragger centered-upload"
                drag
                action="#"
                :on-change="handleFileChange"
                :auto-upload="false"
                :file-list="fileList"
                accept="image/*"
                :before-upload="beforeImageUpload"
                :limit="1"
                :on-exceed="handleExceed"
            >
              <el-icon class="el-icon--upload">
                <upload-filled />
              </el-icon>
              <div class="el-upload__text">
                将图片拖到此处，或<em>点击上传</em>
              </div>
              <template #tip>
                <div class="el-upload__tip">
                  只能上传jpg/png格式图片，且不超过5MB（仅限1张图片）
                </div>
              </template>
            </el-upload>
          </el-col>
        </el-row>

        <!-- 第二段内容行 - 左对齐标签 -->
        <el-row class="form-row">
          <el-col :span="6" class="label-col left-align">
            <span class="form-label">第二段文字内容：</span>
          </el-col>
          <el-col :span="18" class="content-col">
            <el-input
                v-model="form.paragraph2"
                type="textarea"
                :rows="4"
                placeholder="请输入第二段文字内容"
                class="content-textarea"
            />
          </el-col>
        </el-row>

        <!-- 按钮行 -->
        <el-row class="form-row button-row">
          <el-col :span="24" class="button-col">
            <div class="buttons-container">
              <el-button
                  class="reset-btn"
                  @click="handleReset"
              >
                重置
              </el-button>
              <el-button
                  type="danger"
                  class="submit-btn"
                  @click="handleSubmit"
                  :loading="isSubmitting"
              >
                提交
              </el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <el-dialog
        v-model="resultDialogVisible"
        :title="resultDialogTitle"
        width="30%"
    >
      <span>{{ resultDialogMessage }}</span>
      <template #footer>
        <div style="text-align: center">
          <el-button @click="resultDialogVisible = false">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { UploadFilled } from '@element-plus/icons-vue'
import type { UploadFile, UploadFiles, UploadUserFile } from 'element-plus'
import { newsUploadTask } from "~/api/newsApi";
import { ElMessage } from 'element-plus'

const router = useRouter()

const form = reactive({
  publish_time: '',
  title: '',
  paragraph1: '',
  paragraph2: ''
})

const fileList = ref<UploadUserFile[]>([])
const currentFile = ref<File | null>(null)
const isSubmitting = ref(false)
const resultDialogVisible = ref(false)
const resultDialogTitle = ref('')
const resultDialogMessage = ref('')
const uploadFormRef = ref()

const handleFileChange = (file: UploadFile, files: UploadFiles) => {
  if (files.length > 1) {
    fileList.value = [files[files.length - 1]] // 只保留最新上传的文件
    currentFile.value = files[files.length - 1].raw as File
  } else {
    fileList.value = files as UploadUserFile[]
    currentFile.value = file.raw as File
  }
}

const handleExceed = () => {
  ElMessage.warning('只能上传一张图片，请先删除当前图片再上传新的')
}

const beforeImageUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    showResultDialog('错误', '只能上传图片格式文件')
    return false
  }
  if (!isLt5M) {
    showResultDialog('错误', '图片大小不能超过5MB!')
    return false
  }
  return isImage && isLt5M
}

const handleSubmit = async () => {
  try {
    isSubmitting.value = true

    // 验证必填字段
    if (!form.publish_time || !form.title || !form.paragraph1 || !currentFile.value) {
      showResultDialog('错误', '请填写所有必填字段(时间、标题、第一段内容和配图)')
      return
    }

    const formData = new FormData()
    formData.append('id', 'x')
    formData.append('image1', currentFile.value)
    formData.append('publish_time', form.publish_time)
    formData.append('title', form.title)
    formData.append('paragraph1', form.paragraph1)

    // 第二段内容可选
    if (form.paragraph2) {
      formData.append('paragraph2', form.paragraph2)
    }

    // 调用API上传
    const response = await newsUploadTask(formData)

    if (response?.success) {
      showResultDialog('成功', '新闻上传成功！')
      handleReset() // 上传成功后重置表单
    } else {
      showResultDialog('错误', response?.msg || '新闻上传失败，请重试')
    }

  } catch (error) {
    showResultDialog('错误', '新闻上传失败，请重试')
  } finally {
    isSubmitting.value = false
  }
}

const handleReset = () => {
  fileList.value = []
  currentFile.value = null
  form.publish_time = ''
  form.title = ''
  form.paragraph1 = ''
  form.paragraph2 = ''
  uploadFormRef.value?.resetFields()
}

const showResultDialog = (title: string, message: string) => {
  resultDialogTitle.value = title
  resultDialogMessage.value = message
  resultDialogVisible.value = true
}
</script>

<style scoped>
.upload-container {
  display: flex;
  justify-content: center;
  margin: 0 100px;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f7fa;
}

.upload-box {
  width: 700px;
  padding: 40px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  text-align: center;
}

.logo {
  margin-bottom: 30px;
  font-size: 32px;
  font-weight: bold;
}

.logo-cloud {
  color: #606266;
}

.upload-form {
  margin-top: 10px;
  max-width: 600px;
  margin-left: auto;
  margin-right: auto;
}

/* 网格布局样式 */
.form-row {
  margin-bottom: 22px; /* 行间距 */
  display: flex;
  width: 100%;
}

.label-col {
  display: flex;
  align-items: center; /* 标签垂直居中 */
  padding-right: 15px;
}

.content-col {
  display: flex;
  align-items: center; /* 内容垂直居中 */
}

/* 标签对齐样式 */
.right-align {
  justify-content: flex-end; /* 右对齐标签 */
}

.left-align {
  justify-content: flex-start; /* 左对齐标签 */
}

.form-label {
  font-size: 16px;
  color: #606266;
  line-height: 1.5;
}

/* 按钮行样式 */
.button-row {
  margin-top: 30px; /* 与上方内容间距 */
}

.button-col {
  display: flex;
  justify-content: center; /* 按钮容器居中 */
}

.buttons-container {
  display: flex;
  gap: 20px;
}

/* 输入组件样式 */
:deep(.el-input),
:deep(.el-textarea),
:deep(.el-date-editor),
:deep(.el-upload) {
  width: 100%;
}

.centered-upload {
  width: 100%;
}

.content-textarea {
  width: 100%;
  min-height: 100px;
}

/* 按钮样式 */
.submit-btn {
  width: 150px;
  background-color: #1b9382;
  border: none;
  color: white;
}

.reset-btn {
  width: 150px;
  border: 1px solid #1b9382;
  color: #1b9382;
}

/* 文件上传样式 */
:deep(.el-upload-dragger) {
  width: 100%;
  padding: 15px;
}

:deep(.el-upload-dragger:hover),
:deep(.el-upload:focus .el-upload-dragger) {
  border-color: #1b9382;
  color: #1b9382;
}

:deep(.el-upload-dragger .el-icon--upload) {
  color: #1b9382;
}

:deep(.el-upload__tip) {
  margin-top: 10px;
  color: #909399;
  font-size: 14px;
}
</style>